package redis

import (
	"github.com/gomodule/redigo/redis"
	"time"
)

var rPool *redis.Pool

func Init(address string, maxIdle, maxActive int) error {

	rPool = &redis.Pool{
		MaxIdle:   maxIdle,
		MaxActive: maxActive,
		//IdleTimeout: MaxIdleTimeout * time.Second,
		Wait: true,
		Dial: func() (redis.Conn, error) {
			conn, err := redis.Dial("tcp", address)
			//redis.DialPassword(conf["Password"].(string)),
			//redis.DialDatabase(int(conf["Db"].(int64))),
			//redis.DialConnectTimeout(timeout*time.Second),
			//redis.DialReadTimeout(timeout*time.Second),
			//redis.DialWriteTimeout(timeout*time.Second))
			if err != nil {
				return nil, err
			}
			return conn, nil
		},
	}

	var r = Conn()
	defer r.Close()

	_, err := r.Do("SET", "test", "test", "EX", 1)
	return err
}

func Conn() redis.Conn {
	return rPool.Get()
}

func Get(key string) ([]byte, error) {

	var r = Conn()
	defer r.Close()

	var reply, err = r.Do("GET", key)
	if reply == nil {
		return nil, err
	}

	return redis.Bytes(reply, err)
}

func Set(key string, value []byte, expire int) (err error) {

	var r = Conn()
	defer r.Close()

	if expire <= 0 {
		_, err = r.Do("SET", key, value)
	} else {
		_, err = r.Do("SET", key, value, "EX", expire)
	}

	return err
}

//func SetOnDate(key string, value []byte) error {
//
//	var tomorrow = time.Now().AddDate(0, 0, 1)
//	var year, month, day = tomorrow.Date()
//	var sec = time.Date(year, month, day, 0, 0, 0, 0, time.Local).Sub(time.Now()).Seconds()
//
//	var r = Conn()
//	defer r.Close()
//
//	var _, err = r.Do("SET", key, value, "EX", int(sec))
//	return err
//}

// set success return true
func TodaySet(key string) (bool, error) {

	var r = Conn()
	defer r.Close()

	// one day one login record
	var tomorrow = time.Now().AddDate(0, 0, 1)
	var year, month, day = tomorrow.Date()
	var sec = time.Date(year, month, day, 0, 0, 0, 0, time.Local).Sub(time.Now()).Seconds()

	var res, err = r.Do("SET", key, "t", "EX", int(sec), "NX")
	var OK, success = res.(string)
	return success && OK == "OK", err
}

func GetTodayNumber(key string) int {

	var r = Conn()
	defer r.Close()

	var reply, err = r.Do("GET", key)
	if err != nil {
		panic(err)
	}

	n, _ := redis.Int(reply, err)
	return n
}

func SetTodayNumber(key string, n int) {

	var r = Conn()
	defer r.Close()

	var tomorrow = time.Now().AddDate(0, 0, 1)
	var year, month, day = tomorrow.Date()
	var expire = int(time.Date(year, month, day, 0, 0, 0, 0, time.Local).Sub(time.Now()).Seconds())

	_, _ = r.Do("SET", key, n, "EX", expire)
}
